<?php

namespace App\Kuafu\Mqtt\Service;


use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Dashboard\Service\PosOnlineService;
use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Mqtt\Model\Queue;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\WaiMai\Enum\WaiMaiCacheEnum;
use App\Kuafu\WaiMai\Service\WaiMaiOrderService;
use App\Library\FeiShu\SendFs;
use App\Support\MQTT;
use App\Kuafu\Base\Service\BaseService;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Kuafu\GeneralFs\BuildFs;

class MqttWebHookService extends BaseService
{
    protected string $event;

    public function setEvent(string $event): MqttWebHookService
    {
        $this->event = $event;
        return $this;
    }


    /**
     * @throws Exception
     */
    public function deal(array $requestData)
    {
        switch ($this->event) {
            case 'client.connected':
                $this->clientConnected($requestData);
                break;
            case 'client.disconnected':
                $this->clientDisConnected($requestData);
                break;
            default:
                break;
        }
    }

    /**
     * MQTT 连接事件
     *
     * @param array $requestData
     * @return void
     * @throws Exception
     */
    private function clientConnected(array $requestData)
    {
        $formatRequestData['username'] = $requestData['username'] ?? '';

        $shopInfo = ShopService::getShopInfo((int)$formatRequestData['username']);
        if (empty($shopInfo)) {
            $content = vsprintf("mqtt username: %s 对应门店不存在", $formatRequestData['username']);
        } else {
            $content = vsprintf("%s[%s] 已连接", [$shopInfo['name'], $shopInfo['id']]);

            PosOnlineService::setPosOnlineStatusTime($shopInfo['id'], 86400 * 7); // 7天时间
        }

        BuildFs::newRobot(SendFs::ROBOT_POS_MQTT_STATUS)
               ->setTitleContent('MQTT连接通知', $content)
               ->setUrl('登录MQ(线上)', 'http://ops.kuafu.tech:18083')
               ->send();
    }

    /**
     * MQTT 离线事件
     *
     * @param array $requestData
     * @return void
     * @throws Exception
     */
    private function clientDisConnected(array $requestData)
    {
        // TODO 设置 mqtt 在线状态

        $formatRequestData['username'] = $requestData['username'] ?? '';
        $formatRequestData['reason']   = $requestData['reason'] ?? '';

        $shopInfo = ShopService::getShopInfo((int)$formatRequestData['username']);
        if (empty($shopInfo)) {
            $content = vsprintf("mqtt username: %s 对应门店不存在", $formatRequestData['username']);
        } else {
            $mqttOutDelayMinutes = ConfigModel::getConfigByTypeKeyOne('posConfig', 'mqttOutDelayMinutes');
            $delayMinutes        = $mqttOutDelayMinutes['value'] ?? 5;
            $content             = vsprintf("%s[%s] 断开连接, 原因: %s, %s",
                [
                    $shopInfo['name'],
                    $shopInfo['id'],
                    $formatRequestData['reason'],
                    $delayMinutes . '分钟后收银机状态离线'
                ]);

            PosOnlineService::setPosOnlineStatusTime($shopInfo['id'], (int)bcmul($delayMinutes, 60)); // 300s 后过期
        }
        BuildFs::newRobot(SendFs::ROBOT_POS_MQTT_STATUS)
               ->setTitleContent('MQTT断开连接通知', $content)
               ->send();
    }
}
